package com.example.controller;

import com.example.entity.*;
import com.example.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrdersDetailService ordersDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private ScoreDetailService scoreDetailService;

    //        @GetMapping("/buy")
    @RequestMapping("/add")
    public ModelAndView buy(int gid, HttpServletRequest request, Model model) {
        ModelAndView mv = new ModelAndView();
        try {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            Goods goods=goodsService.getGoodsById(gid);
            System.out.println(user.getUid());
            // 1. 准备基础数据
            String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            double price = goods.getPrice().doubleValue();
            // 计算积分（商品价格的0.1倍）
            double scoreToAdd = price * 0.1;
            double newScore = user.getScore() + scoreToAdd;

            // 2. 创建主订单
            Orders orders = new Orders();
            orders.setUid(user.getUid());
            orders.setCreatetime(createTime);
            orders.setGname(goods.getGname());
            orders.setPaymoney(goods.getPrice());
            orders.setPaystatus(1);

            // 更新用户积分
            user.setScore((int)newScore);
            userService.updateScore(user.getUid(), (int)newScore);

            recordScoreChange(user.getUid(), orders.getOid(), goods.getGid(), "BUY_GOODS", scoreToAdd, user.getScore() - scoreToAdd, newScore);

            // 3. 保存订单并获取生成的ID
            this.ordersService.addOrders(orders);
            //4.生成订单详情
            OrdersDetail ordersDetail = new OrdersDetail();

            int oid=orders.getOid();
            ordersDetail.setGid(gid);
            ordersDetail.setUid(user.getUid());
            ordersDetail.setGname(goods.getGname());
            ordersDetail.setImg(goods.getImg());
            ordersDetail.setGprice(goods.getPrice());
            ordersDetail.setOid(oid);
            ordersDetailService.addDetail(ordersDetail);
            model.addAttribute("oid", ordersDetail.getOid());
            model.addAttribute("name", goods.getGname());
            model.addAttribute("paymoney",ordersDetail.getGprice());
            model.addAttribute("order", orders);
            model.addAttribute("goods", goods);
            mv.setViewName("student/pay");
        } catch (Exception e) {
            e.printStackTrace();
            mv.setViewName("error");
        }
        return mv;
    }
    @RequestMapping("exchange")
    public ModelAndView exchange(int gid, HttpServletRequest request, Model model) {
        ModelAndView mv = new ModelAndView();
        try {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            Goods goods=goodsService.getGoodsById(gid);
            System.out.println(user.getUid());
            // 1. 准备基础数据
            String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 检查用户积分是否足够
            if (user.getScore() < goods.getScorerequired()) {
                throw new RuntimeException("积分不足，无法兑换");
            }

            double scorerequired = goods.getScorerequired();
            // 计算积分变化
            double scoreToDeduct = -goods.getScorerequired();
            double newScore = user.getScore() + scoreToDeduct; // 注意这里是加分负数，即减分

            // 2. 创建主订单
            Orders orders = new Orders();
            orders.setUid(user.getUid());
            orders.setCreatetime(createTime);
            orders.setPaymoney(BigDecimal.valueOf(0.0));
            orders.setPaystatus(1);

            // 更新用户积分
            user.setScore((int)newScore);
            userService.updateScore(user.getUid(), (int)newScore);

            recordScoreChange(user.getUid(), orders.getOid(), goods.getGid(), "EXCHANGE", scoreToDeduct, user.getScore() - scoreToDeduct, newScore);

            // 3. 保存订单并获取生成的ID
            this.ordersService.addOrders(orders);
            //4.生成订单详情
            OrdersDetail ordersDetail = new OrdersDetail();

            int oid=orders.getOid();
            ordersDetail.setGid(gid);
            ordersDetail.setUid(user.getUid());
            ordersDetail.setGname(goods.getGname());
            ordersDetail.setImg(goods.getImg());
            ordersDetail.setGprice(goods.getPrice());
            ordersDetail.setOid(oid);
            ordersDetailService.addDetail(ordersDetail);
            model.addAttribute("order", orders);
            model.addAttribute("goods", goods);
            mv.setViewName("student/exchangegoods");
        } catch (Exception e) {
            e.printStackTrace();
            mv.setViewName("error");
        }
        return mv;
    }
    public void recordScoreChange(int uid,int oid,int gid,String changetype,double scorechange,double beforescore,double afterscore){
        ScoreDetail scoreDetail = new ScoreDetail();
        scoreDetail.setOid(oid);
        scoreDetail.setGid(gid);
        scoreDetail.setUid(uid);
        scoreDetail.setChangetype(changetype);
        scoreDetail.setScorechange(scorechange);
        scoreDetail.setBeforescore(beforescore);
        scoreDetail.setAfterscore(afterscore);
        scoreDetail.setUpdatetime(new Date());
        scoreDetailService.insert(scoreDetail);

    }
    @RequestMapping("/detail")
    public String detail(Model model,HttpSession session,int oid){
        User user = (User) session.getAttribute("user");
        System.out.println("aaaaaaaa"+user.getUid());
        OrdersDetail ordersDetails=ordersDetailService.getAllDetailByOid(oid);
        Orders orders=ordersService.getAllOrdersByOid(oid);
        model.addAttribute("orders",orders);
        model.addAttribute("ordersDetails",ordersDetails);
        model.addAttribute("uid", user.getUid());
        return "student/OD";
    }
    @RequestMapping("/list")
    public String list(Model model, HttpSession session,
                       @RequestParam(required = false) Integer uid) {  // 1. 改为 Integer

        // 2. 获取用户信息
        User user = (User) session.getAttribute("user");

        // 3. 处理 uid 为 null 的情况（从 session 获取）
        if (uid == null) {
            if (user == null) {
                return "/student/home"; // 未登录则跳转
            }
            uid = user.getUid();
        }

        // 4. 查询订单
        List<Orders> orders = ordersService.getAllOrdersByUid(uid);
        model.addAttribute("orders", orders != null ? orders : new ArrayList<>());

        return "student/orders";
    }
}